package com.sengled.cloud.biz.union.mgt.service.util;

import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.*;

import java.io.File;
import java.io.InputStream;

public class S3Util {

	private static S3Util s3Util;
	private static AmazonS3 s3;

	public static S3Util getInstance(String region){
		if(s3Util == null){
			 s3 = AmazonS3ClientBuilder.standard().withCredentials(DefaultAWSCredentialsProviderChain.getInstance()).withRegion(region).build();
			s3Util = new S3Util();
		}
		return s3Util;
	}
	// 创建桶
	public static void createBucket(String bucketName) {
//		s3.setRegion(usWest2);
		s3.createBucket(bucketName);
	}

	// 查询是否有对应名字的桶
	public static boolean queryBucketExist(String bucketName) {
//		s3.setRegion(usWest2);
		return s3.doesBucketExist(bucketName);
	}

	// 删除桶
	public static void deleteBucket(String bucketName) {
		s3.deleteBucket(bucketName);
	}

	// 向桶里存放文件
	public static void putObject2Bucket(String bucketName, String key, File file)
			throws AmazonClientException, AmazonServiceException {
//		s3.setRegion(usWest2);
		s3.putObject(new PutObjectRequest(bucketName, key, file));
	}

	// 从桶里获取文件
	public static InputStream getObjectFromBucket(String bucketName, String key)
			throws Exception {
//		s3.setRegion(usWest2);
		S3Object object = s3.getObject(new GetObjectRequest(bucketName, key));
		return object.getObjectContent();
	}

	// 删除文件
    public static void deleteObject2Bucket(String bucketName, String key)
            throws AmazonClientException, AmazonServiceException {
//        s3.setRegion(usWest2);
        s3.deleteObject(new DeleteObjectRequest(bucketName, key));
    }

    //批量删除
    public static void deleteObjects2Bucket(String bucketName, String[] keys)
            throws AmazonClientException, AmazonServiceException {
//        s3.setRegion(usWest2);
        s3.deleteObjects(new DeleteObjectsRequest(bucketName).withKeys(keys));
    }

}
